<template>
  <div class="icon-card-toolbar">
    <div
      class="icon-card-toolbar__button"
      @click.stop="onCopy">
      <icon
        name="copy"
        :size="14" />
      复制
    </div>
    <div
      class="icon-card-toolbar__button"
      @click.stop="onDownload">
      <icon
        name="download"
        :size="14" />
      下载
    </div>
  </div>
</template>

<script>
/**
 * Toolbar.vue - Icon 示例卡片组件 - Toolbar 子组件
 * =============================================================
 * Created By: Yaohaixiao
 * Update: 2023.1.18
 */
import Icon from '@/components/BaseIcon'
import { copyToClipboard, createAndDownloadFile } from '@/utils/utils'

export default {
  name: 'CardToolbar',
  componentName: 'CardToolbar',
  components: {
    Icon
  },
  props: {
    name: {
      type: String,
      default: ''
    },
    symbol: {
      type: String,
      default: ''
    }
  },
  methods: {
    copy(name) {
      copyToClipboard(name)
      this.$message.success({
        round: true,
        message: `图标名 ${name} 已复制到粘贴板！`
      })
    },
    download() {
      const pattern = /<symbol(([\s\S])*?)>(.*?)<\/symbol>/
      const symbol = this.symbol
      const paths = symbol.match(pattern)[3]
      const size = symbol.match(/viewBox="0 0 (.*?)"/)[1].split(' ')
      const originWidth = parseInt(size[0], 10)
      const originHeight = parseInt(size[1], 10)
      const width = originWidth > 200 ? 200 : originWidth
      const height = originHeight > 200 ? 200 : originHeight
      const svg =
        '<!-- Generated by icons.toolkit.vue -->\n' +
        '<svg xmlns="http://www.w3.org/2000/svg" width="' +
        width +
        '" height="' +
        height +
        '" viewBox="0 0 ' +
        originWidth +
        ' ' +
        originHeight +
        '">\n' +
        '<title>' +
        this.name +
        '</title>\n' +
        paths +
        '\n' +
        '</svg>'

      createAndDownloadFile(`${this.name}.svg`, svg)
    },
    onCopy() {
      this.copy(this.name)
    },
    onDownload() {
      this.download()
    }
  }
}
</script>

<style scoped lang="less">
@import 'toolbar';
</style>
